package controller;

import helper.Calendr;
import helper.Formatter;
import helper.UserSession;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import databeans.Customer;
import databeans.Employee;
import databeans.Fund;
import databeans.FundHistory;
import model.FundDAO;
import model.FundHistoryDAO;
import model.Model;

public class EmployeeCreateFundAction extends Action{
    private FundDAO fundDAO;
    private FundHistoryDAO fundHistoryDAO;

    public EmployeeCreateFundAction(Model model) {
        fundDAO = model.getFundDAO();
        fundHistoryDAO = model.getFundHistoryDAO();
    }
    
    public String getName() {
        return "employeeCreateFund.do";
    }
    

    public String perform(HttpServletRequest request) {
        //ATTENTION
        // define target page
        String loginPage = "employee/employee-login.jsp";
        String originPage = "employee/view-funds.jsp";
        String successPage = originPage; 
        
        //set the employee
        Employee employee = null;
        Customer customer = null;
        Fund fund = null;

        //errors and messages will be stored here
        //resetting those containers
        List<String> errors = new ArrayList<String>();
        List<String> messages = new ArrayList<String>();
   
        //define the error and message
        request.setAttribute("errors", errors);
        request.setAttribute("messages", messages);
        request.setAttribute("page", "view-funds");
        
        Fund[] fundsList = null;
		try {
			fundsList = fundDAO.getFunds();
		} catch (DAOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
        if (fundsList == null) {
            messages.add("There is no fund currently available to be seen");
            return successPage;
        }

        // Attach (this copy of) the employee bean to the session
        request.setAttribute("fundsList", fundsList);
        
        //get all the parameter from the form
        String requestType = request.getParameter("Submit");      
        String fundName = request.getParameter("txtFundName");
        String fundSymbol = request.getParameter("txtFundSymbol");
        String fundPrice = request.getParameter("txtFundPrice");
  
        //reload the form field
        request.setAttribute("txtFundName", fundName);
        request.setAttribute("txtFundSymbol", fundSymbol);
        request.setAttribute("txtFundPrice", fundPrice);
        

        
        //check if employee has been logged in
        //request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
        //request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
        //So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
        employee = UserSession.getLoggedInEmployee(request);
        if (employee == null) {
            errors.add("You need to log in");
            return loginPage ;
        }
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer != null) {
            request = UserSession.removeCustomerFromSession(request);
            errors.add("This section is closed for customer");
            return loginPage;
        }
        
        //validate if user has necessary qualification
        //check the session

        // check for get or post request
        //if there is no parameter get passed, return to origin page
        if (requestType == null) {
            messages.add("To create a new Fund, fill in the form below");
            return originPage;     
        }
        
        //validate the input
        if (fundName.trim().equals("")) {
            messages.add("Enter the Fund Name");
            errors.add("Current Fund Name field is still empty");
            return originPage;
        }
        
        if (fundSymbol.trim().equals("")) {
            messages.add("Enter fund symbol");
            errors.add("Current Fund Symbol field is still empty");
            return originPage;
        }
        
        
        if (fundSymbol.trim().length() > 5) {
            messages.add("Fund ticker must not exceed 5 character");
            errors.add("Current fund ticker is longer than 5 characters");
            return originPage;
        }
        if (fundPrice.trim().equals("")) {
            messages.add("Enter fund price");
            errors.add("Current Fund price field is still empty");
            return originPage;
        }
        
        try {
            Double.parseDouble(fundPrice);
        }
        catch(NumberFormatException nFE) {
        	messages.add("Enter fund price");
            errors.add("Current fund price field is not a proper number");
            return originPage;
        }
        
        //check if double value inputted is A double
        if (!Formatter.isDouble(fundPrice)){
            //messages.add("You must input a number in amount field");
            errors.add("Invalid input in Amount field. Please check.");
            return originPage;
        }
        
        //check if double has 2 decimal place
        if(Formatter.numberOfDecimal(fundPrice)>2) {
            messages.add("CFA only tracks amount up to two decimal place. Please reenter the amount");
            errors.add("Accuracy could not be captured");
            return originPage;
        }
        
        //ensure no negative number
        if ( Double.parseDouble(fundPrice) <= 0.00 ){
            //messages.add("The amount should not be negative");
            errors.add("Invalid input for fund price. Please check.");
            return originPage;
        }

        
        // at this stage, all input validation should have been done
        try {
            
            //check of symbol has already exist
            fund = fundDAO.lookup(fundSymbol);
            
            //check if symbol is unique
            if (fund!=null){
                messages.add("The symbol of each fund must be unique");
                errors.add("Symbol has already exist. Choose another Symbol");
                return originPage;
            }
            
            //create fund object
            fund = new Fund();
            fund.setName(fundName);
            fund.setSymbol(fundSymbol.toUpperCase());

            //push those fund object into database
            int fID = fundDAO.createReturnID(fund);
            //Also create fundhistory
            fundHistoryDAO.createByAlvin(new FundHistory(fID,Calendr.getTodaysDate(),Formatter.prepCashFromView(fundPrice)));

            
            // Attach (this copy of) the logged in employee bean to the session
            HttpSession session = request.getSession(true); 
            Employee loggedInEmployee = (Employee) session.getAttribute("employee");
            session.setAttribute("employee", loggedInEmployee );
            
            //set the welcome message
            messages.add("Succesfully created new fund <b>" + fund.getName() + "</b> with ticker <b>" + fund.getSymbol() + "</b>, of price <b>$"+fundPrice+"</b>");
            request.setAttribute("txtFundName", "");
            request.setAttribute("txtFundSymbol", "");
            request.setAttribute("txtFundPrice", "");
            
            try {
    			fundsList = fundDAO.getFunds();
    		} catch (DAOException e1) {
    			e1.printStackTrace();
    		}
    		request.setAttribute("fundsList", fundsList);
    		
            return successPage;

        } catch (Exception e) {
        	e.printStackTrace();
            errors.add("Unable to create new fund");
            return originPage;
        }

    }
}